package com.changgou.pay.service.impl;

import com.changgou.pay.service.WXPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: HuangFu
 * @Date: 2020/2/19 10:25
 * @Description:
 */
@Service
public class WXPayServiceImpl implements WXPayService {
    @Autowired
    private WXPay wxPay;

    @Value("${wxpay.notify_url}")
    private String notify_url;

    @Override
    public Map nativePay(String orderId, Integer money) {
        Map<String, String> map = new HashMap<>(16);
        //商品详情
        map.put("body","畅购");
        //商户订单号
        map.put("out_trade_no",orderId);

        //金额处理需要高精度类型处理
        //默认单位 元
        BigDecimal payMoney = new BigDecimal("0.01");
        //元转分
        BigDecimal fen = payMoney.multiply(new BigDecimal("100"));
        //保留小数位，取整
        fen = fen.setScale(0,BigDecimal.ROUND_UP);
        //支付金额，本地测试默认
        map.put("total_fee",String.valueOf(fen));

        //终端标识
        map.put("spbill_create_ip","127.0.0.1");
        map.put("notify_url",notify_url);
        map.put("trade_type","NATIVE");

        try {
            return  wxPay.unifiedOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map orderQuery(String orderId) {
        Map<String, String> map = new HashMap<>(16);
        //商户订单号
        map.put("out_trade_no",orderId);
        try {
            return  wxPay.orderQuery(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map closeOrder(String orderId) {
        Map<String, String> map = new HashMap<>(16);
        //商户订单号
        map.put("out_trade_no",orderId);
        try {
            return  wxPay.closeOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
